const { DataTypes, where } = require("sequelize");
const sequelize = require("../config/sequelize");
const User = require("./user");
const Food = require("./food");
const FoodUseNum = require("./foodusenum");

const FoodRecord = sequelize.define(
  "FoodRecord",
  {
    time: {
      type: DataTypes.STRING,
      allowNull: false,
      comment: "饮食记录时间",
    },
    unit: {
      type: DataTypes.STRING,
      allowNull: false,
      defaultValue: "克",
      comment: "饮食记录单位",
    },
    num: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 100,
      comment: "饮食记录数量",
    },
    heat: {
      type: DataTypes.INTEGER,
      allowNull: false,
      comment: "饮食记录热量",
    },
    recordDate: {
      type: DataTypes.STRING,
      allowNull: false,
      comment: "饮食记录时间",
    },
    carbohydrate: {
      type: DataTypes.DOUBLE,
      defaultValue: 0,
    },
    protein: {
      type: DataTypes.DOUBLE,
      defaultValue: 0,
    },
    fat: {
      type: DataTypes.DOUBLE,
      defaultValue: 0,
    },
  },
  {
    sequelize: sequelize,
    tableName: "foodrecord",
    underscored: true, //显示在数据库字段为下划线
  }
);

FoodRecord.belongsTo(Food, {
  constraints: false,
  foreignKey: "foodId",
  as: "food",
});
FoodRecord.belongsTo(User, {
  constraints: false,
  foreignKey: "userId",
  as: "user",
});
// 食物的使用记录加一
FoodRecord.afterCreate(async (foodRecord) => {
  const foodUseNum = await FoodUseNum.findOne({
    where: { foodId: foodRecord.foodId, userId: foodRecord.userId },
  });
  if (foodUseNum) {
    await FoodUseNum.increment(
      { num: 1 },
      { where: { foodId: foodRecord.foodId, userId: foodRecord.userId } }
    );
  } else {
    await FoodUseNum.create({
      num: 1,
      foodId: foodRecord.foodId,
      userId: foodRecord.userId,
    });
  }
});

module.exports = FoodRecord;
